package com.ll.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ll.common.constant.ProductConstant;
import com.ll.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.ll.gulimall.product.dao.AttrGroupDao;
import com.ll.gulimall.product.dao.CategoryDao;
import com.ll.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.ll.gulimall.product.entity.AttrGroupEntity;
import com.ll.gulimall.product.entity.CategoryEntity;
import com.ll.gulimall.product.service.CategoryService;
import com.ll.gulimall.product.vo.AttrAttrGroupRelationVo;
import com.ll.gulimall.product.vo.AttrRespVo;
import com.ll.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.product.dao.AttrDao;
import com.ll.gulimall.product.entity.AttrEntity;
import com.ll.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Resource
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {

        //1.保存基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            //2.保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //属性Id
            relationEntity.setAttrId(attrEntity.getAttrId());
            //属性分组Id
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(relationEntity);
        }
    }

    /**
     * 根据分类Id查询规格属性
     *
     * @param params
     * @param catelogId
     * @param type
     * @return
     */
    @Override
    public PageUtils queryPageBaseList(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type",
                "base".equalsIgnoreCase(type) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //根据分类Id查询
        if (catelogId != null && catelogId != 0L) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        //根据检索条件查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            //attr_id  or  attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> attrEntityList = page.getRecords();
        //封装需要返回的数据
        List<AttrRespVo> attrRespVos = attrEntityList.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //封装当前规格的分组名称
            if ("base".equalsIgnoreCase(type)) {
                if (attrEntity.getAttrId() != null) {
                    Long attrId = attrEntity.getAttrId();//利用属性Id从中间表查询属性分组Id
                    AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                    //属性分组Id
                    if (relationEntity != null) {
                        Long attrGroupId = relationEntity.getAttrGroupId();
                        //根据属性分组Id查询出该属性分组的名称
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        if (attrGroupEntity != null) {
                            //得到分组名称封装
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                    }
                }
            }
            //封装当前规格的分类名称
            if (attrEntity.getCatelogId() != null) {
                Long attrEntityCatelogId = attrEntity.getCatelogId();
                //根据分类id查询该分类名称
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntityCatelogId);
                if (categoryEntity != null) {
                    //封装名称返回
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }

            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //设置分组Id  在关联表查询
        if (attrRespVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null) {
                //设置分组Id
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                //设置分组名称
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //设置分类完成路径
        Long catelogId = attrEntity.getCatelogId();
        if (catelogId != null) {
            Long[] catelogPath = categoryService.findCatelogPath(catelogId);
            attrRespVo.setCatelogPath(catelogPath);
            CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
            if (categoryEntity != null) {
                //设置分类名称
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //1.先修改基本信息
        this.updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            if (count > 0) {
                //修改
                //2.修改关联表信息 修改分组Id
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            }
            if (count == 0) {
                //新增关联表信息 新增分组Id
                relationDao.insert(relationEntity);
            }

        }


    }

    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {


        List<Long> attrIds = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId)).stream().map(relation -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());

        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);

        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteBatchRelation(AttrAttrGroupRelationVo[] vos) {


        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((vo) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, entity);
            return entity;
        }).collect(Collectors.toList());

        relationDao.deleteBatchRelation(entities);

    }

    @Autowired
    private AttrDao attrDao;

    /**
     * 获取当前分类下没有被其他分组关联的属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNotRelation(Map<String, Object> params, Long attrgroupId) {
        // 1.当前分组只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2.当前分组只能关联别的分组没有引用的属性
        // 2.1获取当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = group.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());
        // 2.2 获取这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        // 2.3 从所属分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 根据AttrId查询 不能被检索的属性 返回该属性的Id
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttr(List<Long> attrIds) {


        return  baseMapper.selectSearchAttr(attrIds);
    }

}